<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box{
            width: 100px;
            height: 100px;
            background: #000;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="box"></div>
<script>
    window.onload=function(){
        var box=document.getElementById("box");
//初始化状态
        var left=false;
        var top=false;
        var right=false;
        var down=false;
//状态1
        document.onkeydown=function(ev){
            var e=ev||event;
            var code=e.keyCode;
            document.title=code;

            switch(code){
                case 37:left=true;break;
                case 38:top=true;break;
                case 39:right=true;break;
                case 40:down=true;break;
            }

        }
//状态2
        document.onkeyup=function(ev){
            var e=ev||event;
            var code=e.keyCode;

            switch(code){
                case 37:left=false;break;
                case 38:top=false;break;
                case 39:right=false;break;
                case 40:down=false;break;
            }

        }

        var timer=setInterval(function(){
            if(left){box.style.left=box.offsetLeft-15+'px';}
            if(top){box.style.top=box.offsetTop-15+'px';}
            if(right){box.style.left=box.offsetLeft+15+'px';}
            if(down){box.style.top=box.offsetTop+15+'px';}
        }, 1000 / 60)
    }
</script>
</body>
</html>